/**
 * Copyright (C), 2015-2020, bogewang
 * FileName: PayContextServiceImpl
 * Author:   foren236598164@aliyun.com
 * Date:     2020/3/4 15:28
 * Description: 支付表单实现类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.bogewang.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bogewang.core.base.BaseApiService;
import com.bogewang.core.base.BaseResponse;
import com.bogewang.pay.entity.PayMentTransacDTO;
import com.bogewang.pay.entity.PaymentChannelEntity;
import com.bogewang.pay.factory.StrategyFactory;
import com.bogewang.pay.mapper.PaymentChannelMapper;
import com.bogewang.pay.service.PayContextService;
import com.bogewang.pay.service.PayMentTransacInfoService;
import com.bogewang.strategy.PayStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * 〈一句话功能简述〉<br> 
 * 〈支付表单实现类〉
 *
 * @author foren236598164@aliyun.com
 * @create 2020/3/4
 * @since 1.0.0
 */
@RestController
public class PayContextServiceImpl extends BaseApiService<JSONObject> implements PayContextService {

    @Autowired
    private PaymentChannelMapper paymentChannelMapper;

    @Autowired
    private PayMentTransacInfoService payMentTransacInfoService;

    @Override
    public BaseResponse<JSONObject> toPayHtml(String channelId, String payToken) {
        // 1.获取渠道的classAddress;
        PaymentChannelEntity paymentChannel = paymentChannelMapper.selectBychannelId(channelId);
        if (paymentChannel == null){
            return setResultError("没有查询到该渠道信息");
        }

        // 2.获取支付参数；
        BaseResponse<PayMentTransacDTO> tokenByPayMentTransac = payMentTransacInfoService.tokenByPayMentTransac(payToken);
        if ( !isSuccess(tokenByPayMentTransac)){
            return setResultError(tokenByPayMentTransac.getRtnMsg());
        }

        PayMentTransacDTO payMentTransacDTO = tokenByPayMentTransac.getData();

        // 3.执行具体的支付渠道的算法获取html表单数据 策略设计模式 使用java反射机制 执行具体方法
        String classAddres = paymentChannel.getClassAddres();
        PayStrategy payStrategy = StrategyFactory.getPayStrategy(classAddres);
        String payHtml = payStrategy.toPayHtml(paymentChannel, payMentTransacDTO);

        // 4.直接返回html
        JSONObject data = new JSONObject();
        data.put("payHtml", payHtml);
        return setResultSuccess(data);
    }
}
